import * as signalR from '@microsoft/signalr'

class SignalRService {
  connection: signalR.HubConnection | null
  inventoryConnection: signalR.HubConnection | null
  isConnected: boolean
  isInventoryConnected: boolean

  constructor() {
    this.connection = null
    this.inventoryConnection = null
    this.isConnected = false
    this.isInventoryConnected = false
  }
  
  async start(): Promise<void> {
    // 如果已经连接，直接返回
    if (this.isConnected && this.connection) {
      console.log('SignalR已经连接，跳过重复连接')
      return
    }
    
    try {
      // 如果存在旧连接，先关闭
      if (this.connection) {
        await this.connection.stop()
      }
      
      // 创建连接
      this.connection = new signalR.HubConnectionBuilder()
        .withUrl('http://localhost:5215/InventoryReadHub', {
          withCredentials: false
        })
        .withAutomaticReconnect()
        .build()

      // 同时连接库存统计Hub
      this.inventoryConnection = new signalR.HubConnectionBuilder()
        .withUrl('http://localhost:5215/InventoryReadHub', {
          withCredentials: false
        })
        .withAutomaticReconnect()
        .build()

      // 设置连接状态监听
      this.connection.onclose(() => {
        this.isConnected = false
        console.log('SignalR连接已断开')
      })

      this.connection.onreconnecting(() => {
        console.log('SignalR正在重连...')
      })

      this.connection.onreconnected(() => {
        this.isConnected = true
        console.log('SignalR重连成功')
      })

      // 设置消息监听器
      this.setupMessageListeners()

      // 启动连接
      await this.connection.start()
      this.isConnected = true
      console.log('SignalR连接成功')

      // 启动库存连接
      await this.inventoryConnection.start()
      this.isInventoryConnected = true
      console.log('库存SignalR连接成功')
      
    } catch (error) {
      console.error('SignalR连接失败:', error)
      throw error
    }
  }


  async JoinGroup(username: string): Promise<void> {
    if (this.connection && this.isConnected) {
      try {
        await this.connection.invoke('JoinGroup', username)
        console.log(`已加入登录通知组: ${username}`)
        // 1. 监听用户登录通知
        this.connection.on('UserLoginNotification', (user) => {
          console.log('🔔 收到用户登录通知:', user)
          console.log('📊 登录详情:', {
            用户名: user.username || '未知',
            登录时间: user.loginTime || new Date().toLocaleString(),
            消息内容: user.message || user,
            完整数据: user
          })
        })
      } catch (error) {
        console.error('加入组失败:', error)
      }
    }
  }

  async sendLoginNotifications(username: string, password: string): Promise<void> {
  if (this.connection && this.isConnected) {
    try {
      await this.connection.invoke('SendLoginNotifications', username,password)
      console.log(`已发送登录通知: ${username}`)
      
    } catch (error) {
      console.error('发送登录通知失败:', error)
    }
  }
  }

  // 设置消息监听器
  private setupMessageListeners(): void {
    if (!this.connection) return

    // 1. 监听用户登录通知
    this.connection.on('UserLoginNotification', (message) => {
      console.log('🔔 收到用户登录通知:', message)
      console.log('📊 登录详情:', {
        用户名: message.username || '未知',
        登录时间: message.loginTime || new Date().toLocaleString(),
        消息内容: message.message || message,
        完整数据: message
      })
    })

    // 2. 监听库存数量占比推送
    this.connection.on('ReceiveInventoryQuantityRatio', (data) => {
      console.log('📈 收到库存数量占比数据:', data)
      console.table(data) // 使用表格格式显示数组数据
    })

    // 3. 监听库存金额占比推送
    this.connection.on('ReceiveInventoryAmountRatio', (data) => {
      console.log('💰 收到库存金额占比数据:', data)
      console.table(data)
    })

    // 4. 监听出入库统计推送
    this.connection.on('ReceiveInOutboundStatistics', (data) => {
      console.log('📦 收到出入库统计数据:', data)
      console.table(data)
    })

    // 5. 监听实时库存更新
    this.connection.on('ReceiveInventoryUpdate', (data) => {
      console.log('🔄 收到实时库存更新:', data)
      console.log('📝 库存变更详情:', {
        产品ID: data.ProductId,
        产品名称: data.ProductName,
        原数量: data.OldQuantity,
        新数量: data.NewQuantity,
        操作类型: data.OperationType,
        操作员: data.OperatorName,
        更新时间: data.UpdateTime
      })
    })

    // 6. 监听综合仪表板数据
    this.connection.on('ReceiveDashboardData', (data) => {
      console.log('🎯 收到综合仪表板数据:', data)
      console.group('📊 仪表板数据详情')
      console.log('数量占比数据:', data.QuantityRatios)
      console.log('金额占比数据:', data.AmountRatios)
      console.log('统计数据:', data.Statistics)
      console.log('总产品数:', data.TotalProducts)
      console.log('总价值:', data.TotalValue)
      console.log('低库存警告:', data.LowStockAlerts)
      console.log('最后更新时间:', data.LastUpdateTime)
      console.groupEnd()
    })

    // 7. 监听通用消息（兼容后端的通用推送）
    this.connection.on('ReceiveMessage', (user, message) => {
      console.log('💬 收到通用消息:', {
        发送者: user,
        消息内容: message,
        接收时间: new Date().toLocaleString()
      })
    })

    // 8. 监听系统通知
    this.connection.on('SystemNotification', (notification) => {
      console.log('🔔 收到系统通知:', notification)
      console.log('通知详情:', {
        类型: notification.type || '系统消息',
        标题: notification.title || '系统通知',
        内容: notification.message || notification,
        时间: notification.timestamp || new Date().toLocaleString()
      })
    })

    console.log('✅ SignalR消息监听器已设置完成')
  }

  // 移除消息监听器
  private removeMessageListeners(): void {
    if (!this.connection) return

    console.log('🚫 正在移除SignalR消息监听器...')
    this.connection.off('UserLoginNotification')
    this.connection.off('ReceiveInventoryQuantityRatio')
    this.connection.off('ReceiveInventoryAmountRatio')
    this.connection.off('ReceiveInOutboundStatistics')
    this.connection.off('ReceiveInventoryUpdate')
    this.connection.off('ReceiveDashboardData')
    this.connection.off('ReceiveMessage')
    this.connection.off('SystemNotification')
    console.log('✅ SignalR消息监听器已移除')
  }

  // 测试方法：手动触发测试消息（用于调试）
  testConsoleMessages(): void {
    console.group('🧪 SignalR消息测试')
    console.log('当前连接状态:', this.isConnected ? '已连接' : '未连接')
    console.log('连接对象:', this.connection)
    
    if (this.isConnected && this.connection) {
      console.log('✅ SignalR已连接，等待接收消息...')
      console.log('📝 可监听的消息类型:')
      console.table([
        { 消息类型: 'UserLoginNotification', 描述: '用户登录通知', 图标: '🔔' },
        { 消息类型: 'ReceiveInventoryQuantityRatio', 描述: '库存数量占比', 图标: '📈' },
        { 消息类型: 'ReceiveInventoryAmountRatio', 描述: '库存金额占比', 图标: '💰' },
        { 消息类型: 'ReceiveInOutboundStatistics', 描述: '出入库统计', 图标: '📦' },
        { 消息类型: 'ReceiveInventoryUpdate', 描述: '实时库存更新', 图标: '🔄' },
        { 消息类型: 'ReceiveDashboardData', 描述: '综合仪表板数据', 图标: '🎯' },
        { 消息类型: 'ReceiveMessage', 描述: '通用消息', 图标: '💬' },
        { 消息类型: 'SystemNotification', 描述: '系统通知', 图标: '🔔' }
      ])
    } else {
      console.warn('⚠️ SignalR未连接，请先登录以建立连接')
    }
    console.groupEnd()
  }

  // 获取连接统计信息
  getConnectionInfo(): object {
    const info = {
      连接状态: this.isConnected ? '已连接' : '未连接',
      连接对象: this.connection ? '存在' : '不存在',
      连接地址: 'http://localhost:5088/UserHub',
      监听器状态: '已设置',
      支持的消息类型: [
        'UserLoginNotification',
        'ReceiveInventoryQuantityRatio', 
        'ReceiveInventoryAmountRatio',
        'ReceiveInOutboundStatistics',
        'ReceiveInventoryUpdate',
        'ReceiveDashboardData',
        'ReceiveMessage',
        'SystemNotification'
      ]
    }
    
    console.log('📊 SignalR连接信息:', info)
    return info
  }

  async stop(): Promise<void> {
    try {
      if (this.connection) {
        // 先移除监听器
        this.removeMessageListeners()
        
        await this.connection.stop()
        this.connection = null
        this.isConnected = false
        console.log('SignalR连接已停止')
      }

      if (this.inventoryConnection) {
        await this.inventoryConnection.stop()
        this.inventoryConnection = null
        this.isInventoryConnected = false
        console.log('库存SignalR连接已停止')
      }
    } catch (error) {
      console.error('停止SignalR连接失败:', error)
    }
  }
}

// 创建单例实例
export const signalRService = new SignalRService()